package unilodge

/*
curl https://www.accommodation.curtin.edu.au/bookingChoicesProperties.html?searchType=Property&searchId=www.stcatherines.accommodation.curtin.edu.au
需求：
 - Home: https://www.accommodation.curtin.edu.au/bookingChoicesProperties.html?searchType=Property&searchId=www.stcatherines.accommodation.curtin.edu.au
 - 采集非waitlist的房源
 - Twin Dolphin Hall: https://www.twindolphins.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x8971504397952565&initialQueryString=searchType%3DProperty%26searchId%3Dwww.twindolphins.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.twindolphins.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.twindolphins.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=759
 - Erica Underwood House: https://www.ericaunderwood.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x8218280056585517&initialQueryString=searchType%3DProperty%26searchId%3Dwww.ericaunderwood.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.ericaunderwood.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.ericaunderwood.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=629
 - Kurrajong Village: https://www.kurrajong.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x0935648947341258&initialQueryString=searchType%3DProperty%26searchId%3Dwww.kurrajong.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.kurrajong.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.kurrajong.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=795
 - Vickery House: https://www.vickeryhouse.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x3615949200647138&initialQueryString=searchType%3DProperty%26searchId%3Dwww.vickeryhouse.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.vickeryhouse.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.vickeryhouse.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=634
 - Guild House :https://www.guildhouse.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x1840774401149547&initialQueryString=searchType%3DProperty%26searchId%3Dwww.guildhouse.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.guildhouse.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.guildhouse.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=633
dev:not yet
download:not yet
*/
// 基础包
import (
	"fmt"

	"github.com/henrylee2cn/pholcus/app/downloader/request" //必需
	. "github.com/henrylee2cn/pholcus/app/spider"           //必需
	"github.com/henrylee2cn/pholcus/common/goquery"         //DOM解析
	"github.com/henrylee2cn/pholcus/logs"
	"github.com/jordan-wright/email"

	"net/http" //设置http.Header
	"net/smtp"
	"strings"
)

const (
	HOME_URL     = "https://www.accommodation.curtin.edu.au/bookingChoicesProperties.html?searchType=Property&searchId=www.guildhouse.curtin.reserve.unilodge.com.au"
	PUBLIC_AGENT = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36"
)

var propertyLinkMap = map[string]string{
	"Twin Dolphin Hall":     "https://www.twindolphins.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x8971504397952565&initialQueryString=searchType%3DProperty%26searchId%3Dwww.twindolphins.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.twindolphins.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.twindolphins.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=759",
	"Erica Underwood House": "https://www.ericaunderwood.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x8218280056585517&initialQueryString=searchType%3DProperty%26searchId%3Dwww.ericaunderwood.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.ericaunderwood.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.ericaunderwood.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=629",
	"Kurrajong Village":     "https://www.kurrajong.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x0935648947341258&initialQueryString=searchType%3DProperty%26searchId%3Dwww.kurrajong.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.kurrajong.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.kurrajong.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=795",
	"Vickery House":         "https://www.vickeryhouse.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x3615949200647138&initialQueryString=searchType%3DProperty%26searchId%3Dwww.vickeryhouse.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.vickeryhouse.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.vickeryhouse.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=634",
	"Guild House":           "https://www.guildhouse.curtin.reserve.unilodge.com.au/bookingSearch.html?id=135x1840774401149547&initialQueryString=searchType%3DProperty%26searchId%3Dwww.guildhouse.curtin.reserve.unilodge.com.au&initialSearchType=Property&initialSearchId=www.guildhouse.curtin.reserve.unilodge.com.au&initialSearchString=&initialPromoCode=&initialCategory=&initialReferer=https%3A%2F%2Fwww.accommodation.curtin.edu.au%2FbookingChoicesProperties.html%3FsearchType%3DProperty%26searchId%3Dwww.guildhouse.curtin.reserve.unilodge.com.au&internationalStudent=Yes&nonStudent=No&under18=No&category=0&noID=noID&fixedStayId=633",
}

func init() {
	UnilodgeRooms.Register()
}

var UnilodgeRooms = &Spider{
	Name:        "UnilodgeRooms",
	Description: "UnilodgeRooms KEYIN: null",
	// Pausetime:    300,
	Keyin:        KEYIN,
	Limit:        LIMIT,
	EnableCookie: false,
	RuleTree: &RuleTree{
		Root: func(ctx *Context) {
			//cookie := "channelid=0; sid=1516785851105118; Hm_lvt_7ed65b1cc4b810e9fd37959c9bb51b31=1516785861; Hm_lpvt_7ed65b1cc4b810e9fd37959c9bb51b31=1516785874; _ga=GA1.2.2140228708.1516785861; _gid=GA1.2.1413734529.1516785861"
			// cookie := "channelid=0; sid=1566311104277914; Hm_lvt_7ed65b1cc4b810e9fd37959c9bb51b31=1566311907; _ga=GA1.2.1804874949.1566311907; _gid=GA1.2.1007360879.1566311907; Hm_lpvt_7ed65b1cc4b810e9fd37959c9bb51b31=1566311918"
			keyIn := strings.Trim(ctx.GetKeyin(), "\r\n\t ")

			if keyIn != "" {
				// cookie = keyIn
			}

			for propertyName, propertyUrl := range propertyLinkMap {
				ctx.AddQueue(&request.Request{
					Url:  propertyUrl,
					Rule: "CHECK_ROOM_AVAILABLE",
					Header: http.Header{
						"User-Agent": []string{PUBLIC_AGENT},
						"Referer":    []string{HOME_URL},
						// "Cookie":     []string{cookie},
						// "Upgrade-Insecure-Requests": []string{"1"},
						// "Accept-Language":           []string{"zh-CN,zh;q=0.8"},
					},
					Temp: map[string]interface{}{
						"propertyName": propertyName,
						"keyIn":        keyIn,
					},
				})
			}

		},

		Trunk: map[string]*Rule{
			"CHECK_ROOM_AVAILABLE": {
				ItemFields: []string{
					"PropertyName",
					"RoomName",
					"Available",
					"Price",
					"CheckSpecial",
					"Text",
				},
				ParseFunc: func(ctx *Context) {
					// cookie := ctx.GetCookie()
					propertyName := ctx.GetTemp("propertyName", "").(string)
					keyIn := ctx.GetTemp("keyIn", "").(string)
					query := ctx.GetDom()
					logs.Log.Warning("a property:%v start-------------", propertyName)
					availableRooms := make([]string, 0)
					unavailableRooms := make([]string, 0)
					query.Find("#paymentPageContainer").Find(".choicesRooms").Find(".choicesRateDetail").Each(func(j int, roomDom *goquery.Selection) {
						roomName := ""
						price := ""
						checkSpecial := ""
						text := ""
						waitlistOnlyMark := "AVAILABLE"

						text = strings.Trim(roomDom.Find(".choicesRoomRateText").Text(), "\t\r\n ") //with Waitlist Only in it
						if wi := strings.Index(text, "Waitlist Only"); wi > 0 {
							waitlistOnlyMark = "Waitlist Only"
						}

						roomName = strings.Trim(roomDom.Find(".choicesRateLine2").Text(), "\t\r\n ")
						checkSpecial, _ = roomDom.Find(".choicesSpecial").Attr("value")
						price = strings.Trim(roomDom.Find(".choicesRatePriceLine1").Text(), "\t\r\n ")

						ctx.Output(map[int]interface{}{
							0: propertyName,
							1: roomName,
							2: waitlistOnlyMark,
							3: price,
							4: checkSpecial,
							5: text,
						})

						logs.Log.Warning("a room:%v -> %v(%s) - %v - %v - %v", propertyName, roomName, waitlistOnlyMark, price, checkSpecial, text)

						// 如果可预定，则发邮件提示
						roomContent := fmt.Sprintf("a room is Available:%v -> %v(%s) - %v - %v - %v", propertyName, roomName, waitlistOnlyMark, price, checkSpecial, text)
						if waitlistOnlyMark == "AVAILABLE" {
							availableRooms = append(availableRooms, roomContent)
						} else {
							unavailableRooms = append(unavailableRooms, roomContent)
						}
					})

					//email notice
					emailContent := ""
					if len(availableRooms) > 0 {
						emailContent += "availableRooms: " + strings.Join(availableRooms, ";\r\n")
					}
					if len(unavailableRooms) > 0 {
						// emailContent += "unavailableRooms: " + strings.Join(unavailableRooms, ";\r\n")
					}
					if emailContent != "" {
						emailNotice("Unilodge Room Available Notice by Bot - "+propertyName, emailContent, keyIn)
					}

				},
			},
		},
	},
}

func emailNotice(title, text, auth string) {

	enc := ""
	from := ""
	if auth != "" {
		auths := strings.Split(auth, ":")
		if len(auths) >= 2 {
			from = auths[0]
			enc = auths[0]
		}
	}
	e := email.NewEmail()
	e.From = fmt.Sprintf("uxff <%s>", from)
	e.To = []string{"545845496@qq.com"}
	// e.Bcc = []string{"test_bcc@example.com"}
	// e.Cc = []string{"test_cc@example.com"}
	e.Subject = title //"Unilodge Room Available Notice by Bot"
	e.Text = []byte(text)
	// e.HTML = []byte(fmt.Sprintf("<p>a room is Available:%v -> %v(%s) - %v - %v - %v<p>", propertyName, roomName, waitlistOnlyMark, price, checkSpecial, text))
	err := e.Send("smtp.qq.com:25", smtp.PlainAuth("", from, enc, "smtp.qq.com"))

	logs.Log.Informational("send email done. %v", err)
}
